package com.henry.base.concurrency.aio2;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.TimeUnit;

public class SocketChannelReadHandler implements CompletionHandler<Integer,StringBuffer> {
    private AsynchronousSocketChannel socketChannel;
    private ByteBuffer buffer;

    public SocketChannelReadHandler(AsynchronousSocketChannel socketChannel, ByteBuffer buffer) {
        this.socketChannel = socketChannel;
        this.buffer = buffer;
    }

    @Override
    public void completed(Integer result, StringBuffer attachment) {
        if (result == -1) {
            try {
                this.socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        this.buffer.flip();
        byte[] bytes = new byte[16];
        this.buffer.get(bytes, 0, result);
        this.buffer.clear();
        try {
            String context = new String(bytes, 0, result, "UTF-8");
            attachment.append(context);
            System.out.println("当前传输的结果:"+attachment);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (attachment.indexOf("over") == -1) {
            this.socketChannel.read(this.buffer, 3l,TimeUnit.SECONDS,attachment, this);
//            return;
        }else {
            this.buffer.clear();
            System.out.println("客户端发来的消息:"+attachment);
            //业务处理  省略

            ByteBuffer sendBuffer = null;
            try {
                sendBuffer=ByteBuffer.wrap("你好,这是服务端返回数据".getBytes());
                socketChannel.write(sendBuffer);
//                socketChannel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            attachment = new StringBuffer();
            this.socketChannel.read(this.buffer, 3l,TimeUnit.SECONDS,attachment, this);
        }

    }

    @Override
    public void failed(Throwable exc, StringBuffer attachment) {
        System.out.println("==发现客户端异常关闭,服务端将关闭tcp通道");
        try {
            this.socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
